﻿using JinYuan.Helper;
using JinYuan.MES.Enums;
using JinYuan.MES.Models;
using JinYuan.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace JinYuan.MES
{
    public class MesDataProcess : IMes
    {
        private static LoggerHelp _logger = new LoggerHelp();

        #region 1、登录验证
        /// <summary>
        /// 登录MES验证
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="equipNum"></param>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <param name="resJson"></param>
        /// <returns></returns>
        public bool LoginEnyity(string url, string siteCode, string lineCode, string equipNum, string userName, string passWord, string UserCardID, ref string Mesage)
        {
            bool res = false;
            string resJson = "";
            try
            {
                var webApi = new MESApiHelper();
                var model = new LoginEnyity
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    userName = userName,
                    passWord = passWord,
                    userCardID = null// UserCardID
                };

                var nowDate = DateTime.Now;
                var postData = JsonConvert.SerializeObject(model);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postData);
                sw.Stop();

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }
                var res1 = ReturnMesMsg<MesResponse>(result);
                if (res1 == null || !res1.success || !string.IsNullOrEmpty(res1.code) || !string.IsNullOrEmpty(res1.message))
                {
                    var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
                    Mesage = res1.message;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口：{url},请求数据为：{postData}\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时：{sw.ElapsedMilliseconds}ms,返回结果：{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    res = true;
                    Mesage = res1.message;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用员工权限校验接口:{url},请求数据为:{postData}\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\员工权限校验\{nowDate.ToString("HH")}.txt", resJson);
                }
            }
            catch (Exception ex)
            {
                resJson = $"调用员工权限校验接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("调用员工权限校验接口", ex);
            }

            return res;
        }
        #endregion

        #region 2、获取MES参数请求
        /// <summary>
        /// 获取MES参数请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="equipNum"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="resJson"></param>
        /// <returns></returns>
        public ParamReturnData GetParamSetRequest(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, ref string Mesage)
        {
            string resJson = "";
            try
            {
                var model = new
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    materialCode = materialCode,
                    userName = userName
                };

                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(model);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();
                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备参数设定值请求接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备参数设定值请求\{nowDate.ToString("HH")}.txt", resJson);
                    return null;
                }

                var res1 = ReturnMesMsg<ParamReturnData>(result);
                if (res1.success)
                {
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备参数设定值请求接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备参数设定值请求\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    var resData = res1 == null ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备参数设定值请求接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备参数设定值请求\{nowDate.ToString("HH")}.txt", resJson);
                }
                return res1;
            }
            catch (Exception ex)
            {
                resJson = $"设备参数设定值请求接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("设备参数设定值请求接口", ex);
            }


            return null;
        }
        #endregion

        #region 3、参数变更请求
        /// <summary>
        /// 参数变更请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="equipNum"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="paramChangeItems"></param>
        /// <param name="Mesage"></param>
        /// <returns></returns>
        public bool ParamChange(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List<TagListItem> paramChangeItems, ref string Mesage)
        {
            bool res = false;
            string resJson = "";
            try
            {
                var model = new ParamChange
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    materialCode = materialCode,
                    userName = userName,
                    changeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    tagGroupCode = "",
                    tagGroupDescription = "",
                };

                model.tagList = new List<TagListItem>();
                model.tagList.Add(new TagListItem
                {
                    tagCode = "",
                    unitBefore = "",
                });

                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(model);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();


                var resData = result == "" ? "" : result;
                resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用参数设定值变更接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                TxtHelper.WriteTxt($@"D:\APILog\MesLogs\{nowDate.ToString("yyyyMMdd")}\参数设定值变更\{nowDate.ToString("HH")}.txt", resJson);

            }
            catch (Exception ex)
            {
                resJson = $"参数设定值变更接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("参数设定值变更接口", ex);
            }

            return res;

        }
        #endregion

        #region 4、单个上传（只上传卷芯码，不上传托杯码）
        /// <summary>
        /// 单个上传（只上传卷芯码，不上传托杯码）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="equipNum"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="BarCode"></param>
        /// <param name="resJson"></param>
        /// <param name="mesResType"></param>
        /// <returns>{"rows":[{"code":null,"success":true,"message":null,"identification":"InsertAt20231218095755934","containerCode":null,"category":null}],"success":true,"total":1}
        /// </returns>
        public bool SingleCellInStation(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, string BarCode, ref string Mesage, ref MesResType mesResType)
        {
            bool res = false;
            string resJson = "";
            mesResType = MesResType.D;//默认为OK   EVEDL14L2JECX01
            try
            {
                var webApi = new MESApiHelper();
                var model = new SingleCellInStation
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    materialCode = materialCode,
                    userName = userName,
                    identification = BarCode,
                    productType = "MB56"
                };



                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(model);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();

                long outTime = sw.ElapsedMilliseconds;
                if (outTime > 1000)
                {
                    LoggerHelp.WriteLog($"预焊进站PC<=>MES上传耗时:{outTime}ms,电芯码:{BarCode}", "MESTime");
                }

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }

                var res1 = ReturnMesMsg<MesResponseIn>(result);
                if (res1.success)
                {
                    res = true;
                    GetInMesResType(res1, BarCode, ref Mesage, ref mesResType);
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    GetInMesResType(res1, BarCode, ref Mesage, ref mesResType);
                    var resData = res1 == null ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }

            }
            catch (Exception ex)
            {

                Mesage = "调用进站接口超时或MES无返回信息!";
                mesResType = MesResType.B;
                resJson = $"产品进站信息（组装）接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("产品进站信息（组装）接口", ex);
            }

            return res;
        }
        #endregion

        #region 5、复投单个上传（只上传条码，不上传卷芯码）
        /// <summary>
        /// 复投单个上传（只上传条码，不上传卷芯码）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="equipNum"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="BarCode"></param>
        /// <param name="resJson"></param>
        /// <param name="mesResType"></param>
        /// <returns></returns>
        public bool SingleFTCellInStation(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, string BarCode, ref string Mesage, ref MesResType mesResType)
        {
            bool res = false;
            string resJson = "";
            try
            {
                var webApi = new MESApiHelper();
                var model = new ManyCellInStation
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    materialCode = materialCode,
                    userName = userName,
                };

                //电芯条码
                model.identificationList = new List<string>();
                model.identificationList.Add(BarCode);


                //电芯托杯码
                model.containerCodeList = new List<string>();


                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(model);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();

                long outTime = sw.ElapsedMilliseconds;
                if (outTime > 1000)
                {
                    LoggerHelp.WriteLog($"钢壳进站PC<=>MES上传耗时:{outTime}ms,钢壳码:{BarCode}", "MESTime");
                }

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }

                var res1 = ReturnMesMsg<MesResponseIn>(result);
                if (res1.success)
                {
                    res = true;
                    GetInMesResType(res1, BarCode, ref Mesage, ref mesResType);
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    var resData = res1 == null ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }

            }
            catch (Exception ex)
            {
                resJson = $"产品进站信息（组装）接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("产品进站信息（组装）接口", ex);
            }

            return res;
        }
        #endregion

        #region 6、多个电池进站
        /// <summary>
        /// 多个电池进站
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="equipNum"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="listBar"></param>
        /// <param name="MesMessage"></param>
        /// <param name="mesResType"></param>
        /// <returns></returns>
        public bool ManyCellInStation(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List<string> listBar, ref List<string> MesMessage, ref List<MesResType> mesResType)
        {
            bool res = false;
            string resJson = "";
            MesMessage = GetListString(listBar.Count, "进站失败");
            mesResType = GetMesType(listBar.Count);
            try
            {
                var model = new ManyCellInStation
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    materialCode = materialCode,
                    userName = userName,
                    productType = "OK",
                };

                //电芯条码
                model.identificationList = new List<string>();
                for (int i = 0; i < listBar.Count; i++)
                {
                    model.identificationList.Add(listBar[i]);
                }

                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(model);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();

                long outTime = sw.ElapsedMilliseconds;
                if (outTime > 1000)
                {
                    LoggerHelp.WriteLog($"预焊进站PC<=>MES上传耗时:{outTime}ms,电芯码:{listBar[0]},{listBar[1]},{listBar[2]},{listBar[3]}", "MESTime");
                }

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }

                var res1 = ReturnMesMsg<MesResponseIn>(result);
                bool temple = false;
                if (res1 != null)
                {
                    temple = true;
                }
                if (temple)
                {
                    res = true;
                    //GetInMesResType(res1, listBar, ref MesMessage, ref mesResType);
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    var resData = res1 == null ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品进站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }

            }
            catch (Exception ex)
            {
                resJson = $"产品进站信息（组装）接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("产品进站信息（组装）接口", ex);
            }

            return res;
        }
        #endregion

        #region 7、单个电池出站
        /// <summary>
        /// 单个电池出站
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="userName"></param>
        /// <param name="equipNum"></param>
        /// <param name="lineCode"></param>
        /// <param name="materialCode"></param>
        /// <param name="m"></param>
        /// <param name="type"></param>
        /// <param name="mesage"></param>
        /// <param name="mesResType"></param>
        /// <returns></returns>
        public bool SingleCellOutStation(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, BGearEntity m, int type, string materialLotCodeLocator, ref string mesage, ref MesResType mesResType)
        {
            bool res = false;
            string resJson = "";
            string[] ngCode = new string[1];
            ngCode[0] = "";
            try
            {
                JArray jaContainerCode = new JArray(); //containerCodeAndIdentificationList  

                JArray jaMaterialLotCodeList = new JArray();  //materialLotCodeList 
                JObject jo4 = new JObject();
                jo4.Add("materialLotCode", "");
                jo4.Add("materialLotCodeLocator", materialLotCodeLocator);
                jaMaterialLotCodeList.Add(jo4);


                JArray jaIdentiftyList = new JArray();//identiftyList
                JObject jo3 = new JObject();
                jo3.Add("identification", m.BarCode); //卷心码
                jo3.Add("qualityStatus", m.Result);
                jo3.Add("qrCode", ""); //
                jo3.Add("ngMessage", m.Remark);
                jo3.Add("materialLotList", jaMaterialLotCodeList);
                jaIdentiftyList.Add(jo3);


                JObject jo2 = new JObject();
                jo2.Add("containerCode", "");//托杯码
                jo2.Add("identiftyList", jaIdentiftyList);
                jaContainerCode.Add(jo2);


                JObject jo1 = new JObject();
                jo1.Add("siteCode", siteCode);
                jo1.Add("lineCode", lineCode);
                jo1.Add("equipNum", equipNum);
                jo1.Add("userName", userName);
                jo1.Add("productType", "");
                jo1.Add("completeQty", "");
                jo1.Add("type", 1); //追溯标识替换
                jo1.Add("materialCode", materialCode);
                jo1.Add("containerCodeAndIdentificationList", jaContainerCode);



                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(jo1);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();


                long outTime = sw.ElapsedMilliseconds;
                if (outTime > 1000)
                {
                    LoggerHelp.WriteLog($"钢壳进出站PC<=>MES上传耗时:{outTime}ms,钢壳码:{m.BarCode}", "MESTime");
                }

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }

                var res1 = ReturnMesMsg<MesResponse>(result);
                if (res1.success)
                {
                    res = true;
                    GetOutMesResType(res1, m.BarCode, ref mesage, ref mesResType);
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    var resData = res1 == null ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息\{nowDate.ToString("HH")}.txt", resJson);
                }
            }
            catch (Exception ex)
            {
                resJson = $"产品出站信息（组装）接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("产品出站信息（组装）接口", ex);
            }

            return res;
        }
        #endregion

        #region 8、进出站一体模式(单电池)
        /// <summary>
        /// 进出站一体模式(单电池)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="equipNum"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="m"></param>
        /// <param name="type"></param>
        /// <param name="materialLotCodeLocator"></param>
        /// <param name="mesage"></param>
        /// <param name="mesResType"></param>
        /// <returns></returns>
        public bool SingleCellInAndOutStation(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, BGearEntity m, int type, string materialLotCodeLocator, ref string mesage, ref MesResType mesResType)
        {
            bool res = false;
            string resJson = "";
            string[] ngCode = new string[1];
            ngCode[0] = "";
            try
            {
                JArray jaContainerCode = new JArray(); //containerCodeAndIdentificationList  

                JArray jaMaterialLotCodeList = new JArray();  //materialLotCodeList 
                JObject jo4 = new JObject();
                jo4.Add("materialLotCode", "");
                jo4.Add("materialLotCodeLocator", materialLotCodeLocator);
                jaMaterialLotCodeList.Add(jo4);


                JArray jaIdentiftyList = new JArray();//identiftyList
                JObject jo3 = new JObject();
                jo3.Add("identification", m.BarCode); //卷心码
                jo3.Add("qualityStatus", m.Result);
                jo3.Add("qrCode", ""); //
                jo3.Add("ngMessage", m.Remark);
                jo3.Add("materialLotList", jaMaterialLotCodeList);
                jaIdentiftyList.Add(jo3);


                JObject jo2 = new JObject();
                jo2.Add("containerCode", "");//托杯码
                jo2.Add("identiftyList", jaIdentiftyList);
                jaContainerCode.Add(jo2);


                JObject jo1 = new JObject();
                jo1.Add("siteCode", siteCode);
                jo1.Add("lineCode", lineCode);
                jo1.Add("equipNum", equipNum);
                jo1.Add("userName", userName);
                jo1.Add("productType", "");
                jo1.Add("completeQty", "");
                jo1.Add("type", 1); //追溯标识替换
                jo1.Add("materialCode", materialCode);
                jo1.Add("containerCodeAndIdentificationList", jaContainerCode);



                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(jo1);

                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();


                long outTime = sw.ElapsedMilliseconds;
                if (outTime > 1000)
                {
                    LoggerHelp.WriteLog($"钢壳进出站PC<=>MES上传耗时:{outTime}ms,钢壳码:{m.BarCode}", "MESTime");
                }

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用进出站一体信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进出站一体信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }

                var res1 = ReturnMesMsg<MesResponse>(result);
                if (res1.success)
                {
                    res = true;
                    GetOutMesResType(res1, m.BarCode, ref mesage, ref mesResType);
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用进出站一体信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进出站一体信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    var resData = res1 == null ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用进出站一体信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品进出站一体信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
                }
            }
            catch (Exception ex)
            {
                resJson = $"产品进出站一体信息（组装）接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("产品进出站一体信息（组装）接口", ex);
            }

            return res;
        }
        #endregion

        /// <summary>
        /// 多个电芯上传
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool OutboundInformations(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, BGearEntity listBar, ref string MesMessage, ref MesResType mesResType, List<string> NGcodeList, List<string> ngMessage)
        {


            bool res = false;
            string resJson = "";
            MesMessage = "出站失败";
            mesResType = MesResType.B;
            //MesMessage = GetListString(listBar.Count, "出站失败");
            //mesResType = GetMesType(listBar.Count);
            try
            {
                var model = new ManyCellOutStation
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    userName = userName,
                    containerCode = "",
                    materialCode = materialCode,
                    productType = "MB56",                   
                    //completeQty = listBar.Count.ToString(),
                    type = 1
                };

                for (int i = 0; i < 1; i++)
                {
                    //先给mes 传OK
                    model.assembleLineList = new List<assembleLineList>()
                    {
                        new assembleLineList()
                        {
                            identification=listBar.BarCode,
                            qualityStatus = listBar.CSBYHOUTSTATIONJUDGMENTRESULT,
                            qrCode = "",
                            ngCode = NGcodeList,
                            ngMessage = string.Join(",",ngMessage),
                            materialLotList=new List<string>{},
                            materialLotCode= "",
                         }
                    };

                }


                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(model);

                var sw = new Stopwatch();

                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();
                long outTime = sw.ElapsedMilliseconds;
                if (outTime > 1000)
                {
                    LoggerHelp.WriteLog($"外观检出站PC<=>MES上传耗时:{outTime}ms,电芯码:{listBar.BarCode}", "MESTime");
                }

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（包装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息（包装）\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }

                var res1 = ReturnMesMsg<MesResponse>(result);
                if (res1.success)
                {
                    res = true;
                    GetOutMesResType(res1, listBar.BarCode, ref MesMessage, ref mesResType);
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（包装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息（包装）\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    GetOutMesResType(res1, listBar.BarCode, ref MesMessage, ref mesResType);
                    var resData = res1 == null ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（包装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息（包装）\{nowDate.ToString("HH")}.txt", resJson);
                }

            }
            catch (Exception ex)
            {
                resJson = $"产品出站信息（包装）接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("产品出站信息（包装）接口", ex);
            }

            return res;
        }


        //#region 9、多个电池出站
        ///// <summary>
        ///// 多个电池出站
        ///// </summary>
        ///// <param name="url"></param>
        ///// <param name="siteCode"></param>
        ///// <param name="userName"></param>
        ///// <param name="equipNum"></param>
        ///// <param name="lineCode"></param>
        ///// <param name="materialCode"></param>
        ///// <param name="listBar"></param>
        ///// <param name="type"></param>
        ///// <param name="resJson"></param>
        ///// <param name="mesResType"></param>
        ///// <returns></returns>
        //public bool ManyCellOutStation(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List<BGearEntity> list, int type, string materialLotCodeLocator, ref List<string> MesMessage, ref List<MesResType> mesResType)
        //{
        //    DateTime nowDate = DateTime.Now;
        //    string resJson = "";
        //    bool res = false;
        //    MesMessage = GetListString(list.Count, "MES出站失败");
        //    mesResType = GetMesType(list.Count);
        //    try
        //    {
        //        JArray jaContainerCode = new JArray(); //containerCodeAndIdentificationList  
        //        foreach (BGearEntity m in list)
        //        {
        //            JArray jaMaterialLotCodeList = new JArray();  //materialLotCodeList 
        //            JObject jo4 = new JObject();
        //            jo4.Add("materialLotCode", "");
        //            jo4.Add("materialLotCodeLocator", materialLotCodeLocator);
        //            jaMaterialLotCodeList.Add(jo4);


        //            JArray jaIdentiftyList = new JArray();//identiftyList
        //            JObject jo3 = new JObject();
        //            jo3.Add("identification", m.BarCode); //电芯码
        //            jo3.Add("materialLotList", "");
        //            jo3.Add("materialLotCode", "");
        //            jo3.Add("materialLotCodeLocator", "");
        //            jo3.Add("qualityStatus", m.Result);
        //            jo3.Add("qrCode", ""); //
        //            jo3.Add("ngCode",m.ngCode);
        //            jo3.Add("ngMessage", m.Remark);
        //            jo3.Add("materialLotList", jaMaterialLotCodeList);
        //            jaIdentiftyList.Add(jo3);
        //        }

        //        JObject jo1 = new JObject();
        //        jo1.Add("siteCode", siteCode);//工厂代码
        //        jo1.Add("lineCode", lineCode);//产线编号
        //        jo1.Add("equipNum", equipNum);//设备编号
        //        jo1.Add("materialCode", materialCode);//物料编码
        //        jo1.Add("userName", userName);//员工账号
        //        jo1.Add("productType", "");//产品类型
        //        jo1.Add("completeQty", "");//完工数
        //        jo1.Add("containerCode", "");//托盘码
        //        jo1.Add("type", 1); //追溯标识替换

        //        jo1.Add("containerCodeAndIdentificationList", jaContainerCode);


        //        var postcontent = JsonConvert.SerializeObject(jo1);
        //        var sw = new Stopwatch();
        //        sw.Start();
        //        string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
        //        sw.Stop();
        //        long outTime = sw.ElapsedMilliseconds;
        //        if (outTime > 1000)
        //        {
        //            LogHelper.Instance.WriteLog($"预焊出站PC<=>MES上传耗时:{outTime}ms,电芯码:{list[0].BarCode},{list[1].BarCode},{list[2].BarCode},{list[3].BarCode},{list[4].BarCode},{list[5].BarCode},{list[6].BarCode},{list[7].BarCode}", "MESTime");
        //        }

        //        if (string.IsNullOrEmpty(result))
        //        {
        //            string resData = result == "" ? "" : result;
        //            resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
        //            TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
        //            return res;
        //        }

        //        var res1 = ReturnMesMsg<MesResponseOut>(result);
        //        if (res1.success)
        //        {
        //            res = true;
        //            GetOutMesResType(res1, list, ref MesMessage, ref mesResType);
        //            resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
        //            TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
        //        }
        //        else
        //        {
        //            var resData = res1 == null ? "" : result;
        //            resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品出站信息（组装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
        //            TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息（组装）\{nowDate.ToString("HH")}.txt", resJson);
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        resJson = $"产品出站信息（组装）接口发生异常：{ex.Message}";
        //        LogHelper.Instance.WriteEX("产品出站信息（组装）接口", ex);
        //    }

        //    return res;
        //}
        //#endregion

        #region 10、 过程数据上传
        /// <summary>
        /// 过程数据上传
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="userName"></param>
        /// <param name="equipNum"></param>
        /// <param name="lineCode"></param>
        /// <param name="materialCode"></param>
        /// <param name="unloadType"></param>
        /// <param name="productProcessParam"></param>
        /// <param name="resJson"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool ProductProcessParam(string url, string siteCode, string userName, string equipNum, string lineCode, string materialCode, MesUploadType unloadType, List<ProductProcessParam> productProcessParam, ref string resJson)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region 11、结果参数上传
        /// <summary>
        /// 结果参数上传
        /// </summary>
        /// <param name="url"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="equipNum"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="m"></param>
        /// <param name="unloadType"></param>
        /// <param name="Mesage"></param>
        /// <returns></returns>
        public bool ProducResultParam(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, BGearEntity m, MesUploadType unloadType, ref string Mesage)
        {
            bool res = false;
            string resJson = "";
            #region 结果上传MES


            try
            {
                var nowDate = DateTime.Now;
                string sNowDate = nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff");

                var model = new ProductResultParameters
                {
                    equipNum = equipNum,
                    type = unloadType.ToString(),
                    payload = ""
                };
                #region old
                //string ZhongliangA = "";
                //string ZhongliangB = "";
                //string CeHouA = "";
                //string CeHouB = "";
                //string JiXingA = "";
                //string JiXingB = "";
                //string HanYingA = "";
                //string HanYingB = "";
                //string ZhengJiErSiLieA = "";
                //string ZhengJiErSiLieB = "";
                //string BeiJiErSiLieA = "";
                //string BeiJiErSiLieB = "";
                //string ZhengJiErFanA = "";
                //string ZhengJiErFanB = "";
                //string BeiJiErFanA = "";
                //string BeiJiErFanB = "";
                //for (int i = 0; i < 2; i++)
                //{
                //    //芯包重量1判定结果
                //    if (m.list_Data1[i, 10] == 1)
                //    {
                //        if (i == 0)
                //            ZhongliangA = "OK";
                //        else
                //            ZhongliangB = "OK";
                //    }
                //    else if (m.list_Data1[i, 10] == 2)
                //    {
                //        if (i == 0)
                //            ZhongliangA = "NG";
                //        else
                //            ZhongliangB = "NG";
                //    }
                //    //芯包侧厚判定结果
                //    if (m.list_Data1[i, 11] == 1)
                //    {
                //        if (i == 0)
                //            CeHouA = "OK";
                //        else
                //            CeHouB = "OK";
                //    }
                //    else if (m.list_Data1[i, 11] == 2)
                //    {
                //        if (i == 0)
                //            CeHouA = "NG";
                //        else
                //            CeHouB = "NG";
                //    }
                //    //芯包CCD极性检测结果
                //    if (m.list_Data1[i, 12] == 1)
                //    {
                //        if (i == 0)
                //            JiXingA = "OK";
                //        else
                //            JiXingB = "OK";
                //    }
                //    else if (m.list_Data1[i, 12] == 2)
                //    {
                //        if (i == 0)
                //            JiXingA = "NG";
                //        else
                //            JiXingB = "NG";
                //    }
                //    //芯包焊印位置判定结果
                //    if (m.list_Data1[i, 15] == 1)
                //    {
                //        if (i == 0)
                //            HanYingA = "OK";
                //        else
                //            HanYingB = "OK";
                //    }
                //    else if (m.list_Data1[i, 15] == 2)
                //    {
                //        if (i == 0)
                //            HanYingA = "NG";
                //        else
                //            HanYingB = "NG";
                //    }
                //    //芯包正面极耳撕裂判定结果
                //    if (m.list_Data1[i, 16] == 1)
                //    {
                //        if (i == 0)
                //            ZhengJiErSiLieA = "OK";
                //        else
                //            ZhengJiErSiLieB = "OK";
                //    }
                //    else if (m.list_Data1[i, 16] == 2)
                //    {
                //        if (i == 0)
                //            ZhengJiErSiLieA = "NG";
                //        else
                //            ZhengJiErSiLieB = "NG";
                //    }
                //    //芯包背面极耳撕裂判定结果
                //    if (m.list_Data1[i, 17] == 1)
                //    {
                //        if (i == 0)
                //            BeiJiErSiLieA = "OK";
                //        else
                //            BeiJiErSiLieB = "OK";
                //    }
                //    else if (m.list_Data1[i, 17] == 2)
                //    {
                //        if (i == 0)
                //            BeiJiErSiLieA = "NG";
                //        else
                //            BeiJiErSiLieB = "NG";
                //    }
                //    //芯包正面极耳翻折检测结果
                //    if (m.list_Data1[i, 18] == 1)
                //    {
                //        if (i == 0)
                //            ZhengJiErFanA = "OK";
                //        else
                //            ZhengJiErFanB = "OK";
                //    }
                //    else if (m.list_Data1[i, 18] == 2)
                //    {
                //        if (i == 0)
                //            ZhengJiErFanA = "NG";
                //        else
                //            ZhengJiErFanB = "NG";
                //    }
                //    //芯包背面极耳翻折检测结果
                //    if (m.list_Data1[i, 19] == 1)
                //    {
                //        if (i == 0)
                //            BeiJiErFanA = "OK";
                //        else
                //            BeiJiErFanB = "OK";
                //    }
                //    else if (m.list_Data1[i, 19] == 2)
                //    {
                //        if (i == 0)
                //            BeiJiErFanA = "NG";
                //        else
                //            BeiJiErFanB = "NG";
                //    }
                //}
                #endregion
                switch (unloadType)
                {
                    case MesUploadType.DD:
                        var payload1 = new Payload1
                        {
                            siteCode = siteCode,
                            lineCode = lineCode,
                            userName = userName,
                            materialCode = materialCode,
                            carCode = "",
                            collection = "JS",
                            recordDate = sNowDate,
                            qty = 1,
                            containerCode = "",

                        };
                        payload1.identification = new IdentificationListItem
                        {
                            identification = m.BarCode,
                            qualityStatus = "Y",//m.CSBYHOUTSTATIONJUDGMENTRESULT,
                        };

                        payload1.tagDataVOList = GetTagDataVOList(m, equipNum, payload1);
                        
                        model.payload = JsonConvert.SerializeObject(payload1);
                        //payload1= JsonConvert.SerializeObject(payload1);
                        break;

                }


                var postcontent = JsonConvert.SerializeObject(model);
                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();

                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品结果加工参数接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品结果加工参数\{nowDate.ToString("HH")}.txt", resJson);
                    return res;
                }


                var res1 = ReturnMesMsg<MesResponse>(result);
                if (!res1.success)
                {
                    var resData = res1 == null ? "" : JsonConvert.SerializeObject(res1);
                    Mesage = res1.message;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品结果加工参数接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品结果加工参数\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    res = true;
                    Mesage = res1.message;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用产品结果加工参数接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品结果加工参数\{nowDate.ToString("HH")}.txt", resJson);
                }

            }
            catch (Exception ex)
            {
                resJson = $"产品结果加工参数接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("产品结果加工参数接口", ex);
            }
            #endregion
            return res;
        }
        private List<TagDataVOListItem> GetTagDataVOList(BGearEntity m, string equipNum, Payload1 payload1)
        {
            //var AGearList = 
            string insertTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            List<TagDataVOListItem> datavolist = new List<TagDataVOListItem>();

            string strFileName = System.Environment.CurrentDirectory + "\\采集项目表.csv";

            FileStream fileStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader streamReader = new StreamReader(fileStream);
            _ = streamReader.ReadLine();
            while (!streamReader.EndOfStream)
            {
                string line = streamReader.ReadLine();
                string[] keys = line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (keys.Length == 3)
                {
                    var temp = m.GetType().GetProperty(keys[1]).GetValue(m, null);

                    datavolist.Add(new TagDataVOListItem()
                    {
                        tagCode = keys[0],
                        tagValue = temp == null ? "0" : temp.ToString(),//m
                        tagTime = DateTime.Now.ToString(),
                        tagCalculateResult = "Y",
                        tagRemark = keys[2]
                    });
                }
            }
            #region 本地字段没有，手动赋值

            {//非Y项//工序名称
                // 产线名称
                // 设备编号
                //操作员
                //班次
                //生产型号

                // 工厂名称
                datavolist.Add(new TagDataVOListItem()
                {
                    tagCode = "factory_name",
                    tagValue = payload1.siteCode,
                    tagTime = DateTime.Now.ToString(),
                    tagCalculateResult = "",
                    tagRemark = "工厂名称"
                });
                // 工序名称
                datavolist.Add(new TagDataVOListItem()
                {
                    tagCode = "process_name",
                    tagValue = m.CSBYHPROCESSNAME,
                    tagTime = DateTime.Now.ToString(),
                    tagCalculateResult = "",
                    tagRemark = "工序名称"
                });
                // 产线名称
                datavolist.Add(new TagDataVOListItem()
                {
                    tagCode = "production_line_name",
                    tagValue = payload1.lineCode,
                    tagTime = DateTime.Now.ToString(),
                    tagCalculateResult = "",
                    tagRemark = "工序名称"
                });
                // 设备编码
                datavolist.Add(new TagDataVOListItem()
                {
                    tagCode = "equipment_id",
                    tagValue = equipNum,
                    tagTime = DateTime.Now.ToString(),
                    tagCalculateResult = "",
                    tagRemark = "设备编码"
                });
                // 操作员
                datavolist.Add(new TagDataVOListItem()
                {
                    tagCode = "operator",
                    tagValue = payload1.userName,
                    tagTime = DateTime.Now.ToString(),
                    tagCalculateResult = "",
                    tagRemark = "操作员"
                });
                // 班次
                datavolist.Add(new TagDataVOListItem()
                {
                    tagCode = "work_shift",
                    tagValue = m.CSBYHSCHEDULE,
                    tagTime = DateTime.Now.ToString(),
                    tagCalculateResult = "",
                    tagRemark = "班次"
                });
                // 生产型号
                datavolist.Add(new TagDataVOListItem()
                {
                    tagCode = "product_model",
                    tagValue = payload1.materialCode,
                    tagTime = DateTime.Now.ToString(),
                    tagCalculateResult = "",
                    tagRemark = "生产型号"
                });
            }

            #endregion

            return datavolist;
        }
        #endregion

        #region 12、设备状态
        /// <summary>
        /// 设备状态
        /// </summary>
        /// <param name="url"></param>
        /// <param name="equipNum"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="statusCode"></param>
        /// <param name="materialCode"></param>
        /// <param name="userName"></param>
        /// <param name="faultCodes"></param>
        /// <param name="guid"></param>
        /// <param name="resJson"></param>
        /// <returns></returns>
        public bool UploadEquStatus(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, string guid, string statusCode, List<FaultCodeList> faultCodes, ref string Mesage)
        {
            bool res = false;
            string resJson = "";
            try
            {
                DateTime nowDate = DateTime.Now;
                string sNowDate = nowDate.ToString("yyyy/MM/dd HH:mm:ss");
                var parameters = new EqpStatusParam
                {
                    siteCode = siteCode,
                    lineCode = lineCode,
                    equipNum = equipNum,
                    materialCode = materialCode,
                    userName = userName,
                    seatId = "",
                    recordDate = sNowDate,
                    statusCode = statusCode.ToString(),
                    uploadTime = sNowDate,
                    guid = guid
                };


                if (faultCodes != null)
                {
                    parameters.faultCodeList = faultCodes;
                }
                else
                {
                    parameters.faultCodeList = null;
                }

                var postcontent = JsonConvert.SerializeObject(parameters);
                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();



                res = true;
                resJson = $"{sNowDate}:调用设备运行状态接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy/MM/dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
                TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备运行状态\{nowDate.ToString("HH")}.txt", resJson);
            }
            catch (Exception ex)
            {
                resJson = $"设备运行状态接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("设备运行状态接口", ex);
            }

            return res;
        }
        #endregion

        #region 13、设备报警上传接口
        /// <summary>
        /// 设备报警上传接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="equipNum"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="userName"></param>
        /// <param name="materialCode"></param>
        /// <param name="alarmObj"></param>
        /// <param name="guid"></param>
        /// <param name="resJson"></param>
        /// <returns></returns>
        public bool UploadEquAlarm(string url, string siteCode, string lineCode, string equipNum, string materialCode, string userName, List<AlarmData> alarmObj, string guid, ref string mesage)
        {
            bool res = false;
            string resJson = "";
            try
            {
                var nowDate = DateTime.Now;
                if (alarmObj.Count > 0)
                {
                    var model = new UploadAlarmParam
                    {
                        siteCode = siteCode,
                        lineCode = lineCode,
                        equipNum = equipNum,
                        materialCode = materialCode,
                        userName = userName,
                        recordDate = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                        guid = guid,
                        seatId = ""
                    };

                    model.alarmLineList = new List<AlarmLineListItem>();
                    for (int j = 0; j < alarmObj.Count; j++)
                    {
                        AlarmLineListItem alarmList = new AlarmLineListItem();
                        alarmList.alarmEndTime = alarmObj[j].EndTime.ToString();
                        alarmList.alarmType = alarmObj[j].AlarmType;
                        alarmList.alarmName = alarmObj[j].AlarmContent;
                        alarmList.alarmStartTime = alarmObj[j].StartTime.ToString();
                        alarmList.faultCode = alarmObj[j].AlarmCode;
                        model.alarmLineList.Add(alarmList);
                    }
                    var postcontent = JsonConvert.SerializeObject(model);

                    var sw = new Stopwatch();
                    sw.Start();
                    string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                    sw.Stop();


                    res = true;
                    resJson = $"{nowDate.ToString("yyyy/MM/dd HH:mm:ss.fff")}:调用设备报警信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy/MM/dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\报警信息\{nowDate.ToString("HH")}.txt", resJson);
                }
            }
            catch (Exception ex)
            {
                resJson = $"调用设备报警信息接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("调用设备报警信息接口", ex);
            }

            return res;
        }
        #endregion

        #region 14、上传设备能耗数据
        /// <summary>
        /// 上传设备能耗数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="equipNum"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="userName"></param>
        /// <param name="electricMeterNum"></param>
        /// <param name="wattrs"></param>
        /// <param name="resJson"></param>
        /// <returns></returns>
        public bool UploadEquEnergy(string url, string siteCode, string lineCode, string equipNum, string userName, List<string> electricMeterNum, List<WattrMeter> wattrs, ref string resJson)
        {
            bool res = false;

            try
            {
                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(wattrs);


                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();


                res = true;
                resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用设备能耗信息接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{JsonConvert.SerializeObject(result)}";
                TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\设备能耗信息\{nowDate.ToString("HH")}.txt", resJson);
            }
            catch (Exception ex)
            {
                resJson = $"调用设备能耗信息接口：{ex.Message}";
                LoggerHelp.WriteEX("调用设备能耗信息接口", ex);
            }

            return res;
        }
        #endregion

        #region 15、风速仪数据上传至MES
        /// <summary>
        /// 风速仪数据上传至MES
        /// </summary>
        /// <param name="url"></param>
        /// <param name="equipNum"></param>
        /// <param name="antiDustAirSpeedNum"></param>
        /// <param name="collectData"></param>
        /// <param name="resJson"></param>
        /// <returns></returns>
        public bool UploadDeviceCollectData(string url, string equipNum, List<string> antiDustAirSpeedNum, List<float> collectData, ref string mesage)
        {
            bool res = false;
            string resJson = "";
            try
            {
                if (collectData == null) { return false; }
                UploadDeviceCollectData uploadDevice = new UploadDeviceCollectData();
                uploadDevice.appid = "e1012966a936170c6fcab98e24042d10";
                uploadDevice.device_code = equipNum;
                uploadDevice.collect_time = GetUnixTimestamp();

                List<Collect_code_value_list> list = new List<Collect_code_value_list>();
                for (int i = 0; i < collectData.Count; i++)
                {
                    Collect_code_value_list _Value_List = new Collect_code_value_list();
                    _Value_List.target_code = 5;
                    _Value_List.target_value = collectData[i].ToString();
                    _Value_List.target_value_tag = antiDustAirSpeedNum[i];
                    list.Add(_Value_List);
                }
                uploadDevice.collect_code_value_list = list;

                var nowDate = DateTime.Now;
                string postcontent = JsonConvert.SerializeObject(uploadDevice);
                var sw = new Stopwatch();
                sw.Start();
                string result = MESApiHelper.WepPostAPIAsync(url, postcontent);
                sw.Stop();
                resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用风速接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\风速信息\{nowDate.ToString("HH")}.txt", resJson);
            }
            catch (Exception ex)
            {
                resJson = $"调用风速接口：{ex.Message}";
                LoggerHelp.WriteEX("调用风速接口", ex);
            }

            return res;
        }
        #endregion

        #region 16、数据处理逻辑
        /// <summary>
        /// 单电池进站分类
        /// </summary>
        /// <param name="res1"></param>
        /// <param name="BarCode"></param>
        /// <param name="MesMessage"></param>
        /// <param name="mesResType"></param>
        private void GetInMesResType(MesResponseIn res1, string BarCode, ref string MesMessage, ref MesResType mesResType)
        {
            if (res1 != null && res1 != null)
            {
                if (res1.success)
                {
                    mesResType = MesResType.D;
                    MesMessage = "MES进站成功 ";

                }
                else
                {
                    if (res1.category == null)
                    {
                        mesResType = MesResType.B;
                        MesMessage = res1.message;
                    }
                    else
                    {
                        switch (res1.category)
                        {
                            case "A":
                                mesResType = MesResType.A;
                                MesMessage = res1.message;
                                break;
                            case "B":
                                mesResType = MesResType.B;
                                MesMessage = res1.message;
                                break;
                            case "C":
                                mesResType = MesResType.C;
                                MesMessage = res1.message;
                                break;
                            default:
                                mesResType = MesResType.UnKnow;
                                MesMessage = "MES进站失败 ";
                                break;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 多电池进站分类
        /// </summary>
        /// <param name="res1"></param>
        /// <param name="listBar"></param>
        /// <param name="MesMessage"></param>
        /// <param name="mesResType"></param>
        //private void GetInMesResType(MesResponseIn res1, List<string> listBar, ref List<string> MesMessage, ref List<MesResType> mesResType)
        //{
        //    if (res1 != null)
        //    {
        //        for (int i = 0; i < res1.total; i++)
        //        {
        //            for (int j = 0; j < res1.total; j++)
        //            {
        //                if (res1.rows[j].identification == listBar[i])
        //                {
        //                    if (res1.rows[j].success)
        //                    {
        //                        mesResType[i] = MesResType.D;
        //                        MesMessage[i] = "MES进站成功 ";

        //                    }
        //                    else
        //                    {
        //                        if (res1.rows[j].category == null)
        //                        {
        //                            mesResType[i] = MesResType.B;
        //                            MesMessage[i] = res1.rows[j].message;
        //                        }
        //                        else
        //                        {
        //                            switch (res1.rows[j].category)
        //                            {
        //                                case "A":
        //                                    mesResType[i] = MesResType.A;
        //                                    MesMessage[i] = res1.rows[j].message;
        //                                    break;
        //                                case "B":
        //                                    mesResType[i] = MesResType.B;
        //                                    MesMessage[i] = res1.rows[j].message;
        //                                    break;
        //                                case "C":
        //                                    mesResType[i] = MesResType.C;
        //                                    MesMessage[i] = res1.rows[j].message;
        //                                    break;
        //                                default:
        //                                    mesResType[i] = MesResType.UnKnow;
        //                                    MesMessage[i] = "MES进站失败 ";
        //                                    break;
        //                            }
        //                        }
        //                    }


        //                }
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// 单电池出站分类
        /// </summary>
        /// <param name="res1"></param>
        /// <param name="BarCode"></param>
        /// <param name="MesMessage"></param>
        /// <param name="mesResType"></param>
        private void GetOutMesResType(MesResponse res1, string BarCode, ref string MesMessage, ref MesResType mesResType)
        {
            if (res1 != null && res1 != null)
            {
                if (res1.success)
                {
                    mesResType = MesResType.D;
                    MesMessage = "MES出站成功 ";

                }
                else
                {
                    if (res1.category == null)
                    {
                        mesResType = MesResType.B;
                        MesMessage = res1.message;
                    }
                    else
                    {
                        switch (res1.category)
                        {
                            case "A":
                                mesResType = MesResType.A;
                                MesMessage = res1.message;
                                break;
                            case "B":
                                mesResType = MesResType.B;
                                MesMessage = res1.message;
                                break;
                            case "C":
                                mesResType = MesResType.C;
                                MesMessage = res1.message;
                                break;
                            default:
                                mesResType = MesResType.UnKnow;
                                MesMessage = "MES出站失败 ";
                                break;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 多电池出站结果分类
        /// </summary>
        /// <param name="res1"></param>
        /// <param name="list"></param>
        /// <param name="MesMessage"></param>
        /// <param name="mesResType"></param>
        private void GetOutMesResType(MesResponseOut res1, List<BGearEntity> list, ref List<string> MesMessage, ref List<MesResType> mesResType)
        {
            if (res1 != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    for (int j = 0; j < res1.total; j++)
                    {
                        if (res1.rows[j].identification == list[i].BarCode)
                        {
                            if (res1.rows[j].success)
                            {
                                mesResType[i] = MesResType.D;
                                MesMessage[i] = "MES出站成功 ";

                            }
                            else
                            {
                                if (res1.rows[j].category == null)
                                {
                                    mesResType[i] = MesResType.B;
                                    MesMessage[i] = res1.rows[j].message;
                                }
                                else
                                {
                                    switch (res1.rows[i].category)
                                    {
                                        case "A":
                                            mesResType[i] = MesResType.A;
                                            MesMessage[i] = res1.rows[j].message;
                                            break;
                                        case "B":
                                            mesResType[i] = MesResType.B;
                                            MesMessage[i] = res1.rows[j].message;
                                            break;
                                        case "C":
                                            mesResType[i] = MesResType.C;
                                            MesMessage[i] = res1.rows[j].message;
                                            break;
                                        default:
                                            mesResType[i] = MesResType.UnKnow;
                                            MesMessage[i] = "MES出站失败 ";
                                            break;
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }



        /// <summary>
        /// 序列化各类返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ret"></param>
        /// <returns></returns>
        private T ReturnMesMsg<T>(string ret)
        {

            try
            {
                return JsonConvert.DeserializeObject<T>(ret);
            }
            catch (System.Exception ex)
            {
                return default(T);
            }
        }

        public List<MesResType> GetMesType(int Num)
        {
            List<MesResType> mesResTypes = new List<MesResType>();
            for (int i = 0; i < Num; i++)
            {
                mesResTypes.Add(MesResType.B);
            }
            return mesResTypes;
        }


        public List<string> GetListString(int Num, string str)
        {
            List<string> mesResTypes = new List<string>();
            for (int i = 0; i < Num; i++)
            {
                mesResTypes.Add(str);
            }
            return mesResTypes;
        }


        /// <summary>
        ///本地时间为Unix时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetUnixTimestamp()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }

        #endregion

        #region 17、单个电池分档
        /// <summary>
        /// 单个电池分档
        /// </summary>
        /// <param name="url"></param>
        /// <param name="barCode"></param>
        /// <param name="siteCode"></param>
        /// <param name="lineCode"></param>
        /// <param name="userName"></param>
        /// <param name="equipCode"></param>
        /// <param name="materialCode"></param>
        /// <returns></returns>
        public (bool Success, List<string> MesMessage, List<string> MesResType, List<string> mesResFangAnType) MesGrading(
         string url, string barCode, string siteCode, string lineCode, string userName, string equipCode, string materialCode)
        {
            bool res = false; // 操作结果
            string resJson = ""; // 日志信息

            //string mesage = ""; // 消息
            //MesResType mesResType = MesResType.D; // 默认响应类型
            var lstbarCode = new List<string>();
            lstbarCode.Add(barCode);
            List<string> mesage = GetListString(lstbarCode.Count, "分档失败"); // 消息列表
            List<string> mesResType = GetListString(lstbarCode.Count, "NULL"); // 响应类型列表
            List<string> mesResFangAnType = GetListString(lstbarCode.Count, "NULL"); // 新增分档方案响应类型列表

            try
            {
                // 直接构建电池信息列表（对应materiallotCodeList）
                JArray materiallotCodeList = new JArray(lstbarCode);
                JObject gradingParam = new JObject();
                gradingParam.Add("siteCode", siteCode);
                gradingParam.Add("lineCode", lineCode);
                gradingParam.Add("userName", userName);
                gradingParam.Add("equipCode", equipCode);
                gradingParam.Add("recordDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                gradingParam.Add("qty", 1);
                gradingParam.Add("containerCode", "");
                gradingParam.Add("materialCode", materialCode);
                gradingParam.Add("materiallotCodeList", materiallotCodeList);


                // 序列化请求数据
                var nowDate = DateTime.Now;
                var postcontent = JsonConvert.SerializeObject(gradingParam);

                // 记录请求开始时间
                var sw = Stopwatch.StartNew();

                // 调用异步API
                string result = MESApiHelper.WepPostAPIAsync(url,  postcontent);

                // 记录请求结束时间
                sw.Stop();

                // 如果请求耗时超过1秒，记录日志
                long outTime = sw.ElapsedMilliseconds;
                if (outTime > 1000)
                {
                    LoggerHelp.WriteLog($"卷芯分档PC<=>MES上传耗时:{outTime}ms,卷芯码:{string.Join(",", lstbarCode)}", "MESTime");
                   
                }

                // 如果返回结果为空，记录日志并返回
                if (string.IsNullOrEmpty(result))
                {
                    string resData = result == "" ? "" : result;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用分档信息（包装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{resData}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\产品出站信息\{nowDate.ToString("HH")}.txt", resJson);
                    return (res, mesage, mesResType, mesResFangAnType);
                }

                // 解析返回结果 - 修改部分开始
                var res1 = ReturnMesMsg<MesGradingResponse>(result);



                if (res1.success)
                {
                    // 处理单个电池的结果（当只上传一个电池时）
                    for (int i = 0; i < lstbarCode.Count; i++)
                    {
                        string MesGrading = "NULL";
                        string MesGradingFangAn = "NULL";
                        string Mesage = string.Empty;
                        GetGradingMesResType(res1, barCode, ref Mesage, ref MesGrading,ref MesGradingFangAn);
                        mesage[i] = Mesage ?? "分档成功";
                        mesResType[i] = MesGrading;
                        mesResFangAnType[i] = MesGradingFangAn;
                    }
                    res = true;
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用分档信息（包装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\调用分档信息\{nowDate.ToString("HH")}.txt", resJson);
                }
                else
                {
                    // 设置所有电池的错误消息
                    for (int i = 0; i < lstbarCode.Count; i++)
                    {
                        mesage[i] = "分档失败";
                        mesResType[i] = "NULL";
                    }
                    // 如果操作失败，记录日志
                    resJson = $"{nowDate.ToString("yyyy-MM-dd HH:mm:ss.fff")}:调用分档信息（包装）接口:{url},请求数据为:{postcontent},\n{nowDate.AddMilliseconds(sw.ElapsedMilliseconds).ToString("yyyy-MM-dd HH:mm:ss.fff")}:接口耗时:{sw.ElapsedMilliseconds}ms,返回结果:{result}";
                    TxtHelper.WriteTxt($@"D:\APILog\Logs\MesLogs\{nowDate.ToString("yyyyMMdd")}\调用分档信息\{nowDate.ToString("HH")}.txt", resJson);
                }

                // 修改部分结束
            }
            catch (Exception ex)
            {
                // 捕获异常并记录日志
                resJson = $"调用分档信息（包装）接口发生异常：{ex.Message}";
                LoggerHelp.WriteEX("调用分档信息（包装）接口", ex);

            }

            // 返回结果
            return (res, mesage, mesResType, mesResFangAnType);
        }

        /// <summary>
        /// 单电池分档
        /// </summary>
        /// <param name="res1"></param>
        /// <param name="BarCode"></param>
        /// <param name="MesMessage"></param>
        /// <param name="mesResType"></param>
        private void GetGradingMesResType(MesGradingResponse res1, string BarCode, ref string MesMessage, ref string MesGrading,ref string MesGradingFangAn)
        {
            if (res1 != null && res1.rows != null)
            {
                rowsListItem row = null;
                foreach (var item in res1.rows)
                {
                    if (item.identification == BarCode)
                    {
                        row = item;
                        break;
                    }
                }
                if (row != null)
                {
                    MesMessage = row.message.ToString();
                    MesGrading = row.rank;
                    MesGradingFangAn = row.sortingScheme;
                }
                else
                {
                    MesMessage = "返回为空!";
                    MesGrading = "NULL";
                    MesGradingFangAn = "NULL";
                }

            }
        }
        #endregion
    }
}
